package spring.transaction;

import spring.datasource.DataSourceUtils;
import utils.LogUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

public class TransactionContext implements Transaction {

    protected DataSource dataSource;
    private boolean readOnly;

    public TransactionContext(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {
        this.readOnly = readOnly;
        DataSourceUtils.getConnection(dataSource).setReadOnly(readOnly);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return DataSourceUtils.getConnection(dataSource);
    }


    /**
     * 提交数据库事务的方法
     *
     * @throws SQLException 当数据库访问出错时抛出该异常
     */
    @Override
    public void commit() throws SQLException {
        Connection connection = DataSourceUtils.getConnection(dataSource, false);
        if (Objects.isNull(connection)) {
            LogUtils.debug("当前无有效连接。");
            return;
        }
        if (readOnly) {
            connection.rollback();
        } else {
            connection.commit();
        }
    }

    /**
     * 回滚数据库事务的方法
     *
     * @throws SQLException 当数据库访问出错时抛出该异常
     */
    @Override
    public void rollback() throws SQLException {
        Connection connection = DataSourceUtils.getConnection(dataSource, false);
        if (Objects.isNull(connection)) {
            LogUtils.debug("当前无有效连接。");
            return;
        }
        connection.rollback();
    }

    /**
     * 关闭数据库连接的方法
     */
    @Override
    public void close() throws SQLException {
        Connection connection = DataSourceUtils.getConnection(dataSource, false);
        if (Objects.isNull(connection)) {
            LogUtils.debug("当前连接已关闭。");
            return;
        }
        DataSourceUtils.releaseConnection(connection, dataSource);
    }
}
